package com.qiangesoft.ip.util;

import org.springframework.web.bind.annotation.RequestMethod;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * pconline获取IP地址工具类
 *
 * @author qiangesoft
 * @date 2024-02-01
 */
public class IpPconlineUtil {

    public static void main(String[] args) {
        String ip = getIp();
        System.out.println(ip);
        String address = getAddress("171.223.209.192");
        System.out.println(address);
    }

    /**
     * 通过调用接口的方式获取IP
     */
    public static String getIp() {
        try {
            String data = sendRequest("http://whois.pconline.com.cn/ipJson.jsp");
            String ip = data.substring(data.indexOf("ip") + 5, data.indexOf("pro") - 3);
            return ip;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过调用接口根据ip获取归属地
     */
    public static String getAddress(String ip) {
        if (ip == null) {
            return null;
        }

        try {
            String data = sendRequest("http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true");
            String province = data.substring(data.indexOf("pro") + 6, data.indexOf("proCode") - 3);
            String city = data.substring(data.indexOf("city") + 7, data.indexOf("cityCode") - 3);
            String isp = (data.substring(data.indexOf("addr") + 7, data.indexOf("regionNames") - 3)).split(" ")[1];
            return province + "|" + city + "|" + isp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送请求
     *
     * @param url
     * @return
     */
    private static String sendRequest(String url) {
        try {
            // 请求
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod(RequestMethod.GET.name());
            conn.setUseCaches(false);
            conn.setReadTimeout(6000);
            conn.setConnectTimeout(6000);
            conn.setInstanceFollowRedirects(false);
            int code = conn.getResponseCode();
            if (code != 200) {
                return null;
            }

            // 处理结果
            StringBuilder sb = new StringBuilder();
            InputStream inputStream = conn.getInputStream();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}